package online.flowerinsnow.minecraft.bukkit.floweress.command

import online.flowerinsnow.minecraft.bukkit.floweress.core.FlowerEssCore
import online.flowerinsnow.minecraft.bukkit.floweress.message.MessageConfig
import online.flowerinsnow.minecraft.bukkit.floweress.util.CommandUtils
import org.bukkit.Bukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandSender
import org.bukkit.command.TabExecutor
import org.bukkit.entity.Player

class VisibleCommand : TabExecutor {
    override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
        when (args.size) {
            0 -> {
                if (sender !is Player) {
                    sender.sendMessage(MessageConfig.CONSOLE.getMessage())
                    return true
                }
                if (CommandUtils.checkPermissionAndConsole(sender, "floweress.visible.self")) return true
                if (FlowerEssCore.visibleManager.getPlayerVisible(sender)) {
                    FlowerEssCore.visibleManager.showPlayer(sender)
                    sender.sendMessage(MessageConfig.VISIBLE_DISABLE_SELF.getMessage())
                } else {
                    FlowerEssCore.visibleManager.hidePlayer(sender)
                    sender.sendMessage(MessageConfig.VISIBLE_ENABLE_SELF.getMessage())
                }
                return true
            }
            1 -> {
                if (CommandUtils.checkPermissionAndConsole(sender, "floweress.visible.self")) return true
                val target = Bukkit.getPlayerExact(args[0])
                if (target != null) {
                    if (FlowerEssCore.visibleManager.getPlayerVisible(target)) {
                        FlowerEssCore.visibleManager.showPlayer(target)
                        sender.sendMessage(MessageConfig.VISIBLE_DISABLE_OTHER.getMessage()
                                .replace("%(PLAYER)", target.name))
                    } else {
                        FlowerEssCore.visibleManager.hidePlayer(target)
                        sender.sendMessage(MessageConfig.VISIBLE_ENABLE_OTHER.getMessage()
                                .replace("%(PLAYER)", target.name))
                    }
                } else {
                    sender.sendMessage(MessageConfig.TARGETNOTONLINE.getMessage())
                }
                return true
            }
        }
        sender.sendMessage(MessageConfig.VISIBLE_USAGE.getMessage())
        return true
    }

    override fun onTabComplete(sender: CommandSender, command: Command, alias: String, args: Array<out String>): MutableList<String> {
        if (!sender.hasPermission("floweress.visible.other") || args.size != 1) {
            return ArrayList()
        }
        val list = ArrayList<String>()
        Bukkit.getOnlinePlayers().forEach {
            if (it.name.startsWith(args[0], true)) {
                list.add(it.name)
            }
        }
        return list
    }
}